<template>
  <lay-layer
    v-model="localVisible"
    title="地址管理"
    :area="['800px', '600px']"
    :shade="true"
    :shadeClose="false"
    :maxmin="false"
    :resize="false"
  >
    <div class="address-dialog">
      <!-- 地址列表 -->
      <div class="address-list">
        <div class="list-header">
          <span class="title">收货地址</span>
          <lay-button type="primary" size="sm" @click="handleAdd">
            新增地址
          </lay-button>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          加载中...
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="addressList.length === 0" class="empty">
          <div class="empty-text">暂无收货地址</div>
          <lay-button type="primary" size="sm" @click="handleAdd">
            添加第一个地址
          </lay-button>
        </div>
        
        <!-- 地址列表 -->
        <div v-else class="address-items">
          <div 
            v-for="address in addressList" 
            :key="address.id" 
            class="address-item"
            :class="{ 'is-default': address.isDefault }"
          >
            <div class="address-info">
              <div class="name-phone">
                <span class="name">{{ address.receiverName }}</span>
                <span class="phone">{{ address.receiverPhone }}</span>
                <span v-if="address.isDefault" class="default-tag">默认</span>
              </div>
              <div class="address-text">
                {{ address.province }} {{ address.city }} {{ address.district }} {{ address.address }}
              </div>
            </div>
            <div class="address-actions">
              <lay-button size="xs" @click="handleEdit(address)">编辑</lay-button>
              <lay-button 
                v-if="!address.isDefault" 
                size="xs" 
                @click="handleSetDefault(address)"
              >
                设为默认
              </lay-button>
              <lay-button 
                size="xs" 
                type="danger" 
                @click="handleDelete(address)"
              >
                删除
              </lay-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <lay-button @click="handleClose">关闭</lay-button>
      </div>
    </template>
  </lay-layer>

  <!-- 地址编辑弹框 -->
  <lay-layer
    v-model="formVisible"
    :title="formMode === 'create' ? '新增地址' : '编辑地址'"
    :area="['500px', '400px']"
    :shade="true"
    :shadeClose="false"
  >
    <div class="address-form">
      <lay-form :model="formData" ref="formRef">
        <lay-form-item label="收货人" prop="receiverName">
          <lay-input v-model="formData.receiverName" placeholder="请输入收货人姓名" />
        </lay-form-item>
        
        <lay-form-item label="联系电话" prop="receiverPhone">
          <lay-input v-model="formData.receiverPhone" placeholder="请输入联系电话" />
        </lay-form-item>
        
        <lay-form-item label="省份" prop="province">
          <lay-input v-model="formData.province" placeholder="请输入省份" />
        </lay-form-item>
        
        <lay-form-item label="城市" prop="city">
          <lay-input v-model="formData.city" placeholder="请输入城市" />
        </lay-form-item>
        
        <lay-form-item label="区县" prop="district">
          <lay-input v-model="formData.district" placeholder="请输入区县" />
        </lay-form-item>
        
        <lay-form-item label="详细地址" prop="address">
          <lay-textarea 
            v-model="formData.address" 
            placeholder="请输入详细地址"
            :rows="3"
          />
        </lay-form-item>
        
        <lay-form-item label="设为默认">
          <lay-switch 
            :model-value="formData.isDefault === 1" 
            @update:model-value="(value) => formData.isDefault = value ? 1 : 0"
          />
        </lay-form-item>
      </lay-form>
    </div>
    
    <template #footer>
      <div class="form-footer">
        <lay-button @click="formVisible = false">取消</lay-button>
        <lay-button type="primary" @click="handleSubmit" :loading="formLoading">
          {{ formMode === 'create' ? '添加' : '保存' }}
        </lay-button>
      </div>
    </template>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { layer } from '@layui/layui-vue';
import { UserApi } from '@/api/module/user';
import type { UserAddress, CreateUserAddressRequest, UpdateUserAddressRequest } from '@/types/user';

// Props
interface Props {
  visible: boolean;
  userId: number;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
}>();

// 响应式数据
const loading = ref(false);
const addressList = ref<UserAddress[]>([]);
const localVisible = ref(false);

// 表单相关
const formVisible = ref(false);
const formLoading = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const formRef = ref();
const currentAddress = ref<UserAddress | null>(null);

const formData = reactive<CreateUserAddressRequest & UpdateUserAddressRequest>({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  postalCode: '',
  isDefault: 0
});

// 监听props变化
watch(
  () => props.visible,
  (visible) => {
    localVisible.value = visible;
    if (visible && props.userId) {
      fetchAddressList();
    }
  },
  { immediate: true }
);

// 监听本地visible变化
watch(
  localVisible,
  (newVisible) => {
    if (newVisible !== props.visible) {
      emit('update:visible', newVisible);
    }
  }
);

// 获取地址列表
const fetchAddressList = async () => {
  try {
    loading.value = true;
    const response = await UserApi.getUserAddresses(props.userId);
    addressList.value = response.data || [];
  } catch (error) {
    console.error('获取地址列表失败:', error);
    layer.msg('获取地址列表失败', { icon: 2 });
  } finally {
    loading.value = false;
  }
};

// 关闭弹框
const handleClose = () => {
  localVisible.value = false;
};

// 新增地址
const handleAdd = () => {
  formMode.value = 'create';
  currentAddress.value = null;
  resetForm();
  formVisible.value = true;
};

// 编辑地址
const handleEdit = (address: UserAddress) => {
  formMode.value = 'edit';
  currentAddress.value = address;
  Object.assign(formData, {
    receiverName: address.receiverName,
    receiverPhone: address.receiverPhone,
    province: address.province,
    city: address.city,
    district: address.district,
    address: address.address,
    postalCode: address.postalCode || '',
    isDefault: address.isDefault
  });
  formVisible.value = true;
};

// 删除地址
const handleDelete = async (address: UserAddress) => {
  try {
    await layer.confirm(`确定要删除地址吗？`, {
      title: '确认删除',
      btn: ['确定', '取消']
    });
    
    await UserApi.deleteUserAddress(props.userId, address.id);
    layer.msg('删除成功', { icon: 1 });
    fetchAddressList();
    emit('success');
  } catch (error) {
    if (error !== 'cancel') {
      layer.msg('删除失败', { icon: 2 });
      console.error('删除地址失败:', error);
    }
  }
};

// 设为默认地址
const handleSetDefault = async (address: UserAddress) => {
  try {
    await UserApi.setDefaultAddress(props.userId, address.id);
    layer.msg('设置成功', { icon: 1 });
    fetchAddressList();
    emit('success');
  } catch (error) {
    layer.msg('设置失败', { icon: 2 });
    console.error('设置默认地址失败:', error);
  }
};

// 提交表单
const handleSubmit = async () => {
  // 简单验证
  if (!formData.receiverName.trim()) {
    layer.msg('请输入收货人姓名', { icon: 2 });
    return;
  }
  if (!formData.receiverPhone.trim()) {
    layer.msg('请输入联系电话', { icon: 2 });
    return;
  }
  if (!formData.address.trim()) {
    layer.msg('请输入详细地址', { icon: 2 });
    return;
  }

  try {
    formLoading.value = true;

    // 处理提交数据，如果postalCode为空字符串则设为undefined
    const submitData = { ...formData };
    if (!submitData.postalCode || submitData.postalCode.trim() === '') {
      delete submitData.postalCode;
    }

    if (formMode.value === 'create') {
      await UserApi.createUserAddress(props.userId, submitData);
      layer.msg('添加成功', { icon: 1 });
    } else if (formMode.value === 'edit' && currentAddress.value) {
      await UserApi.updateUserAddress(props.userId, currentAddress.value.id, submitData);
      layer.msg('保存成功', { icon: 1 });
    }

    formVisible.value = false;
    fetchAddressList();
    emit('success');
  } catch (error) {
    layer.msg(formMode.value === 'create' ? '添加失败' : '保存失败', { icon: 2 });
    console.error('提交失败:', error);
  } finally {
    formLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    postalCode: '',
    isDefault: 0
  });
};
</script>

<style scoped>
.address-dialog {
  padding: 20px;
}

.address-list {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.loading, .empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.empty-text {
  margin-bottom: 15px;
  font-size: 14px;
}

.address-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background: #fff;
}

.address-item.is-default {
  border-color: #1890ff;
  background: #f6ffed;
}

.address-info {
  flex: 1;
}

.name-phone {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
}

.name {
  font-weight: 500;
  color: #333;
}

.phone {
  color: #666;
  font-size: 14px;
}

.default-tag {
  background: #1890ff;
  color: white;
  padding: 2px 8px;
  border-radius: 3px;
  font-size: 12px;
}

.address-text {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.dialog-footer, .form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.address-form {
  padding: 20px;
}

.address-form :deep(.layui-form-item) {
  margin-bottom: 15px;
}

.address-form :deep(.layui-form-label) {
  width: 80px;
  text-align: right;
}

.address-form :deep(.layui-input-block) {
  margin-left: 90px;
}
</style>